﻿using BusinessEntity;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using BusinessRule.Organization;
using System.Data;
using BusinessRepository;
using learun.util;
using Newtonsoft.Json.Linq;

namespace BusinessRule
{
    public class Files
    {
        public static async Task InsertFiles(FilesEntity files)
        {
            await new RepositoryFactory().BaseRepository().Insert(files);
        }

        public static async Task<string> GetFile(string Menuid, string Filetype,string Code, string Listid)
        {
            string json = "";
            string sql = "select * Files where Menuid='"+Menuid+ "'";
            if(Listid!="")
            {
                sql += " and ListID='" + Listid + "'";
            }
            if (Filetype != "")
            {
                sql += " and FileType='"+Filetype+"'";
            }
            if (Code != "")
            {
                sql += " and Code='" + Code + "'";
            }
            DataTable table = await new RepositoryFactory().BaseRepository().FindTable(sql,null);
            string ids = "{\"fileIds\":[";
            foreach (DataRow row in table.Rows)
            {
                ids += Convert.ToString(row["FileCode"]).Trim() + ",";
            }

            ids = ids.Substring(0, ids.LastIndexOf(","));
            ids += "]}";
            string url = ConfigHelper.GetConfig().IMUrl + "/file/compose";
            json = JavaApi.HttpPost(url, ids);
            return json;
        }

        public static async Task DeleteFile(string FileCode)
        {
            
            string url = ConfigHelper.GetConfig().IMUrl + "/file";
            string json = JavaApi.HttpPost(url, "id="+FileCode);
            JObject jb = JObject.Parse(json);
            if (jb["code"].ToString() == "200")
            {
                string sql = "delete from Files where FileCode='" + FileCode + "'";
                await new RepositoryFactory().BaseRepository().ExecuteSql(sql);
            }
                
        }
    }
}
